import { Dictionary } from "../core/Dictionary";
import PreLoadCountManager from "./PreLoadCountManager";
import { ResManager } from "./ResManager";

export class DynamicResManager {
    private static _instance: DynamicResManager = null;
    private _dictResList: Dictionary<string, Dictionary<string, any>> = null;
    private _nResTotalCount: number = 0;
    private _nResCurrLoadedCount: number = 0;
    private _loadPercentList: Array<number> = null;
    private constructor() {
    }

    public static getInstance(): DynamicResManager {
        if (!DynamicResManager._instance) {
            DynamicResManager._instance = new DynamicResManager();
            DynamicResManager._instance._loadPercentList = new Array<number>();
            DynamicResManager._instance._dictResList = new Dictionary<string, Dictionary<string, any>>();
        }

        return DynamicResManager._instance;
    }

    public preload(filePath: string, callbackFunc: Function = null): void {
        PreLoadCountManager.getInstance().addTotalResCount();

        let loader: any = ResManager.getInstance();
        let that: DynamicResManager = this;

        loader.loadRes(filePath, cc.SpriteAtlas, function (completedCount: number, totalCount: number, item: any) {
            that._loadPercentList.push(Math.floor(completedCount / totalCount * 100));
        }, function (err, asset) {
            PreLoadCountManager.getInstance().addResCurrLoadedCount();
            //cc.log("### DynamicResManager 预加载完成:",filePath);
            //检查资源加载
            if (err) {
                //console.warn( '预加载:',filePath,"失败， 原因:", err );
                return;
            }

            if (!that._dictResList.get(filePath)) {
                that._dictResList.set(filePath, new Dictionary<string, any>());
            }

            let frames: any = asset._spriteFrames;
            let dict: any = that._dictResList.get(filePath);
            for (let key in frames) {
                if ((frames[key] instanceof cc.SpriteFrame)) {
                    dict.set(key, frames[key]);
                }
            }

            if (callbackFunc) callbackFunc();
        });
    }

    public preloadDir(dirPath: string): void {
        PreLoadCountManager.getInstance().addTotalResCount();
        //cc.log("### DynamicResManager 预加载:",dirPath);

        // let loader:any = cc.resources;
        let that: DynamicResManager = this;

        cc.resources.loadDir(dirPath, function (completedCount: number, totalCount: number, item: any) {
            that._loadPercentList.push(Math.floor(completedCount / totalCount * 100));
        }, function (err, asset) {
            PreLoadCountManager.getInstance().addResCurrLoadedCount();
            //cc.log("### DynamicResManager 预加载完成:",dirPath);

            //检查资源加载
            if (err) {
                //console.warn( '预加载:',dirPath,"失败， 原因:", err );
                return;
            }

            if (!that._dictResList.get(dirPath)) {
                that._dictResList.set(dirPath, new Dictionary<string, any>());
            } else {
                return;
            }

            for (let k = 0; k < asset.length; ++k) {
                let res = asset[k];

                if ((res instanceof cc.SpriteFrame)) {
                    that._dictResList.get(dirPath).set(res.name, res);
                } else if (res instanceof dragonBones.DragonBonesAsset) {

                    that._dictResList.get(dirPath).set("DragonBonesAsset", res);
                } else if (res instanceof dragonBones.DragonBonesAtlasAsset) {
                    that._dictResList.get(dirPath).set("DragonBonesAtlasAsset", res);
                }
                else {
                    that._dictResList.get(dirPath).set("", res);
                }
            }
        });
    }

    public getResWithFileName(fileName: string, spriteFrameName: string): cc.SpriteFrame {
        let dict: any = this._dictResList.get(fileName);
        if (!dict) {
            cc.error("找不到资源:" + fileName);
            return null;
        }

        let spFrame: cc.SpriteFrame = dict.get(spriteFrameName);
        return spFrame;
    }

    public getResWithFileName2(fileName: string, spriteFrameName: string): any {
        let dict: any = this._dictResList.get(fileName);
        if (!dict) {
            cc.error("找不到资源:" + fileName);

            this.preloadDir(fileName);
            return null;
        }

        return dict.get(spriteFrameName);
    }

    public getResDictWithFileName(fileName: string): Dictionary<string, cc.SpriteFrame> {
        return this._dictResList.get(fileName);
    }

    public getDetailPercent(): number {
        if (!this._loadPercentList.length) return 0;
        return Math.floor(this._loadPercentList.shift());
    }

    public getResCurrLoadedCount(): number {
        return this._nResCurrLoadedCount;
    }

    public getResTotalCount(): number {
        return this._nResTotalCount;
    }

    public getIsAllLoaded(): boolean {
        return this.getResCurrLoadedCount() >= this.getResTotalCount();
    }

    public clearLoadedDetail(): void {
        this._loadPercentList.length = 0;
    }

    public releaseResWithFileName(filePath: string): void {
        this._dictResList.get(filePath).clear();
        this._dictResList.delete(filePath);
        // cc.loader.releaseResDir(filePath);

    }

    public release(): void {
        if (!this._dictResList) {
            return;
        }

        let outterKeyList = this._dictResList.getKeyList();
        for (let i = 0; i < outterKeyList.length; ++i) {
            let outterKey = outterKeyList[i];
            let dict = this._dictResList[outterKey];
            if (!dict || !(dict instanceof Dictionary)) {
                continue;
            }

            let innerKeyList = dict.getKeyList();
            for (let j = 0; j < innerKeyList.length; ++j) {
                let innerKey = innerKeyList[j];
                let res = dict[innerKey];
                if (!res) {
                    continue;
                }

                cc.resources.release(res);
            }
        }

        this._dictResList.clear();
    }
}
